package com.wy.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;

import cn.hutool.captcha.generator.RandomGenerator;
import com.wy.common.R;

import com.wy.controller.dto.CodeDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 王昭贵
 * @since 2023-01-14
 */
@CrossOrigin
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${petHospital.path}")
    private String basePath;
    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        log.info(file.toString());
        //原始文件名
        String originalFilename = file.getOriginalFilename();//abc.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;//dfsdfdfd.jpg
        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在，需要创建
            dir.mkdirs();
        }
        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }
    /**
     * 文件下载
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {

        File file = new File(basePath + name);
        if (!file.exists()) {
            file = new File(basePath + "moren.jpeg");
        }
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(file);
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /****
     * 请求验证码
     * @return
     * @throws Exception
     */
    @GetMapping("/getCheckCode")
    public R<Object> getVerify() throws Exception {
        //生成验证码图片
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 36,4,99);
        captcha.setFont(new Font("Consolas", Font.BOLD, (int) ((double) 36* 0.75D)));

        captcha.createCode();
        //验证码字符
        String verifyCode = captcha.getCode();
        //拼接固定的接收格式
        String param = "data:image/png;base64," + captcha.getImageBase64();
        String uuid = UUID.randomUUID().toString();
        CodeDTO codeDTO =new CodeDTO();
        codeDTO.setImg(param);
        codeDTO.setImgUUID(uuid);
        redisTemplate.opsForValue().set(uuid, captcha.getCode(), 5, TimeUnit.MINUTES);
        return R.success(codeDTO);
    }

}
